package qc.module.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qc.common.core.exception.QCPromptException;
import qc.common.core.unify.QCUnifyReturnValue;
import qc.common.core.utils.DateUtil;
import qc.module.demo.dto.river.RIVERDto;
import qc.module.demo.dto.rsvr.RSVRDto;
import qc.module.demo.entity.RIVER;
import qc.module.demo.entity.RSVR;
import qc.module.demo.mapper.RIVERMapper;
import qc.module.demo.mapper.RSVRMapper;
import qc.module.demo.repository.RIVERRepository;
import qc.module.demo.repository.RSVRRepository;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;

/**
 * WaterService
 *
 * @author QuCheng Tech
 * @since 2023/9/16
 */
@Service
public class WaterService {
    private RSVRRepository rsvrRepository;
    private RIVERRepository riverRepository;

    @Autowired
    public void setRepository(RSVRRepository rsvrRepository) {
        this.rsvrRepository = rsvrRepository;
    }

    @Autowired
    public void setRepository(RIVERRepository riverRepository) {
        this.riverRepository = riverRepository;
    }

    /**
     * 新增水库水情数据
     *
     * @param dto
     * @return
     */
    public String addRSVR(RSVRDto dto) throws QCPromptException {
        if (dto == null)
            return QCUnifyReturnValue.Warn("对象不能为空");

        // DTO转换为Entity
        RSVR en = RSVRMapper.MAPPER.toEntity(dto);

        if (!StringUtils.isBlank(dto.getTM())) {
            // 时间格式处理
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
            LocalDateTime localDateTime = LocalDateTime.parse(dto.getTM(), formatter);
            String tm = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(localDateTime);
            System.out.println(tm);

            // 时间解析
            Date time;
            try {
                // 解析起始时间和截止时间
                time = DateUtil.parseDate(tm);
                en.setTM(time);
            } catch (Exception e) {
                throw new QCPromptException("时间解析出错");
            }
        }

        // 判断id和时间是否已经存在，已经存在则直接修改，不存在则新增
        if (!hasRSVRExist(dto.getSTCD(), dto.getTM())) {
            if (rsvrRepository.insert(en) < 0x1)
                return QCUnifyReturnValue.Warn("新增失败");
        } else {
            LambdaUpdateWrapper<RSVR> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(RSVR::getSTCD, dto.getSTCD());
            wrapper.eq(RSVR::getTM, dto.getTM());
            rsvrRepository.update(en, wrapper);
        }

        return QCUnifyReturnValue.Success();
    }

    /**
     * 新增河道水情数据
     *
     * @param dto
     * @return
     */
    public String addRIVER(RIVERDto dto) throws QCPromptException {
        if (dto == null)
            return QCUnifyReturnValue.Warn("对象不能为空");

        // DTO转换为Entity
        RIVER en = RIVERMapper.MAPPER.toEntity(dto);

        if (!StringUtils.isBlank(dto.getTM())) {
            // 时间格式处理
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
            LocalDateTime localDateTime = LocalDateTime.parse(dto.getTM(), formatter);
            String tm = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(localDateTime);
            System.out.println(tm);

            //时间解析
            Date time;
            try {
                // 解析起始时间和截止时间
                time = DateUtil.parseDate(tm);
                en.setTM(time);
            } catch (Exception e) {
                throw new QCPromptException("时间解析出错");
            }
        }

        // 判断id和时间是否已经存在，已经存在则直接修改，不存在则新增
        if (!hasRIVERExist(dto.getSTCD(), dto.getTM())) {
            if (riverRepository.insert(en) < 0x1)
                return QCUnifyReturnValue.Warn("新增失败");
        } else {
            LambdaUpdateWrapper<RIVER> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(RIVER::getSTCD, dto.getSTCD());
            wrapper.eq(RIVER::getTM, dto.getTM());
            riverRepository.update(en, wrapper);
        }

        return QCUnifyReturnValue.Success();
    }

    /**
     * 判断水库id与tm是否存在
     *
     * @param rsvrId
     * @return
     */
    public boolean hasRSVRExist(String rsvrId, String tm) {
        LambdaQueryWrapper<RSVR> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RSVR::getSTCD, rsvrId).eq(RSVR::getTM, tm);

        RSVR en = rsvrRepository.selectOne(wrapper);
        if (en != null)
            return true;

        return false;
    }

    /**
     * 判断河道id与tm是否存在
     *
     * @param riverId
     * @return
     */
    public boolean hasRIVERExist(String riverId, String tm) {
        LambdaQueryWrapper<RIVER> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RIVER::getSTCD, riverId).eq(RIVER::getTM, tm);

        RIVER en = riverRepository.selectOne(wrapper);
        if (en != null)
            return true;

        return false;
    }
}
